<template>
  <div style="margin-bottom: 30px">
    <xyEnergyhead>
      <EnergyHead
        title="峰谷平电量电费统计"
        icon="dataCenter"
        :info="info"
        @download-chart="downloadChart"
        @init-chart="initChart"
      ></EnergyHead>
      <div v-if="typeShow" class="chart-container">
        <div ref="peakValleyChart" class="chart-wrapper"></div>
      </div>
      <div v-if="!typeShow" class="table-container">
        <el-table
          :data="tableData"
          style="width: 100%"
          size="large"
          :header-cell-style="{ background: '#0066ff0d', color: '#0066ff' }"
        >
          <el-table-column prop="date" label="时段类型">
            <template slot-scope="scope">
              <span>
                <i
                  class="fas fa-mountain"
                  v-if="scope.row.date === '峰时段'"
                  style="color: #ff4444; margin-right: 8px"
                ></i>
                <i
                  class="fas fa-hill-rockslide"
                  v-else-if="scope.row.date === '平时段'"
                  style="color: #ffaa00; margin-right: 8px"
                ></i>
                <i
                  class="fas fa-valley"
                  v-else-if="scope.row.date === '谷时段'"
                  style="color: #00cc88; margin-right: 8px"
                ></i>
                {{ scope.row.date }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="电量(kWh)"></el-table-column>
          <el-table-column prop="percentage" label="占比"></el-table-column>
          <el-table-column prop="bill" label="电费(元)"></el-table-column>
          <el-table-column prop="price" label="单价(元/kWh)"></el-table-column>
        </el-table>
      </div>
    </xyEnergyhead>
  </div>
</template>

<script>
import xyEnergyhead from "../../components/xy-energy-head.vue";
import EnergyHead from "./EnergyHead.vue";
import * as echarts from "echarts";

export default {
  components: { xyEnergyhead, EnergyHead },
  props: {
    typeShow: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      peakValleyChart: null,
      currentTimeDimension: "day", // 默认显示日维度数据
      chartData: {
        day: {
          labels: Array.from({ length: 24 }, (_, i) => `${i}:00`),
          peakData: Array.from({ length: 24 }, (_, i) => {
            if ((i >= 8 && i < 12) || (i >= 17 && i < 21)) {
              return Math.floor(Math.random() * 30) + 25;
            }
            return 0;
          }),
          flatData: Array.from({ length: 24 }, (_, i) => {
            if ((i >= 6 && i < 8) || (i >= 12 && i < 17) || (i >= 21 && i < 22)) {
              return Math.floor(Math.random() * 20) + 15;
            }
            return 0;
          }),
          valleyData: Array.from({ length: 24 }, (_, i) => {
            if (i >= 22 || i < 6) {
              return Math.floor(Math.random() * 10) + 5;
            }
            return 0;
          }),
        },
        month: {
          labels: Array.from({ length: 30 }, (_, i) => {
            return (i + 1) % 3 === 0 ? `${i + 1}日` : `${i + 1}`;
          }),
          peakData: Array.from({ length: 30 }, (_, i) => {
            const isWeekend = i % 7 === 5 || i % 7 === 6;
            const baseVal = isWeekend ? 120 : 180;
            const randomFactor = Math.floor(Math.random() * 80);
            const weeklyCycle = Math.sin(i * (Math.PI / 7)) * 30;
            const monthlyTrend = (i / 30) * 40;
            return Math.max(60, baseVal + randomFactor + weeklyCycle + monthlyTrend);
          }),
          flatData: Array.from({ length: 30 }, (_, i) => {
            const isWeekend = i % 7 === 5 || i % 7 === 6;
            const baseVal = isWeekend ? 150 : 220;
            const randomFactor = Math.floor(Math.random() * 100);
            const weeklyCycle = Math.sin(i * (Math.PI / 7) + 1) * 40;
            const monthlyTrend = (i / 30) * 50;
            return Math.max(80, baseVal + randomFactor + weeklyCycle + monthlyTrend);
          }),
          valleyData: Array.from({ length: 30 }, (_, i) => {
            const isWeekend = i % 7 === 5 || i % 7 === 6;
            const baseVal = isWeekend ? 80 : 100;
            const randomFactor = Math.floor(Math.random() * 60);
            const weeklyCycle = Math.sin(i * (Math.PI / 7) + 2) * 20;
            const monthlyTrend = (i / 30) * 30;
            return Math.max(40, baseVal + randomFactor + weeklyCycle + monthlyTrend);
          }),
        },
        year: {
          labels: [
            "1月",
            "2月",
            "3月",
            "4月",
            "5月",
            "6月",
            "7月",
            "8月",
            "9月",
            "10月",
            "11月",
            "12月",
          ],
          peakData: [
            5200,
            4800,
            3900,
            3100,
            2900,
            3800,
            5400,
            5600,
            4200,
            3300,
            3100,
            4500,
          ],
          flatData: [
            6100,
            5800,
            4900,
            4100,
            3900,
            4800,
            6300,
            6500,
            5200,
            4300,
            4100,
            5500,
          ],
          valleyData: [
            3500,
            3200,
            2600,
            2200,
            2100,
            2500,
            3600,
            3700,
            2800,
            2300,
            2200,
            3200,
          ],
        },
      },
      tableData: [
        {
          date: "峰时段",
          name: "450",
          percentage: "36%",
          bill: "360",
          price: "0.80",
        },
        {
          date: "平时段",
          name: "520",
          percentage: "41.6%",
          bill: "338",
          price: "0.65",
        },
        {
          date: "谷时段",
          name: "280",
          percentage: "22.4%",
          bill: "140",
          price: "0.50",
        },
      ],
      info: {
        title: "峰谷平电量电费统计详情",
        listInfo: [
          {
            title: "此图表展示了峰、谷、平时段的电量和电费统计信息。",
          },
          {
            title: "不同时段的电价不同，通过优化用电时段可以显著降低电费支出。",
          },
          {
            title: "表格数据展示了各时段的电量占比、电费支出和电价信息。",
          },
        ],
      },
    };
  },
  mounted() {
    if (this.typeShow) {
      this.$nextTick(() => {
        this.initPeakValleyChart();
      });
    }
    this.updateTableData();
  },
  beforeDestroy() {
    if (this.peakValleyChart) {
      this.peakValleyChart.dispose();
    }
  },
  watch: {
    typeShow: {
      handler(newVal) {
        if (newVal) {
          this.$nextTick(() => {
            this.initPeakValleyChart();
          });
        } else {
          if (this.peakValleyChart) {
            this.peakValleyChart.dispose();
            this.peakValleyChart = null;
          }
          this.updateTableData();
        }
      },
      immediate: true,
    },
    currentTimeDimension: {
      handler() {
        if (this.typeShow) {
          this.$nextTick(() => {
            this.initPeakValleyChart();
          });
        } else {
          this.updateTableData();
        }
      },
    },
  },
  methods: {
    initChart() {
      if (this.typeShow) {
        this.initPeakValleyChart();
      } else {
        this.updateTableData();
      }
    },
    switchTimeDimension(dimension) {
      this.currentTimeDimension = dimension;
    },

    updateTableData() {
      // 根据时间维度更新表格数据
      const currentData = this.chartData[this.currentTimeDimension];

      // 计算各时段总电量
      const peakTotal = currentData.peakData.reduce((sum, val) => sum + val, 0);
      const flatTotal = currentData.flatData.reduce((sum, val) => sum + val, 0);
      const valleyTotal = currentData.valleyData.reduce((sum, val) => sum + val, 0);
      const totalEnergy = peakTotal + flatTotal + valleyTotal;

      // 计算各时段总电费
      const peakCost = peakTotal * 0.8;
      const flatCost = flatTotal * 0.65;
      const valleyCost = valleyTotal * 0.5;

      this.tableData = [
        {
          date: "峰时段",
          name: Math.round(peakTotal).toString(),
          percentage: ((peakTotal / totalEnergy) * 100).toFixed(1) + "%",
          bill: Math.round(peakCost).toString(),
          price: "0.80",
        },
        {
          date: "平时段",
          name: Math.round(flatTotal).toString(),
          percentage: ((flatTotal / totalEnergy) * 100).toFixed(1) + "%",
          bill: Math.round(flatCost).toString(),
          price: "0.65",
        },
        {
          date: "谷时段",
          name: Math.round(valleyTotal).toString(),
          percentage: ((valleyTotal / totalEnergy) * 100).toFixed(1) + "%",
          bill: Math.round(valleyCost).toString(),
          price: "0.50",
        },
      ];
    },

    initPeakValleyChart() {
      if (!this.$refs.peakValleyChart) return;

      if (this.peakValleyChart) {
        this.peakValleyChart.dispose();
      }

      this.peakValleyChart = echarts.init(this.$refs.peakValleyChart);

      const currentData = this.chartData[this.currentTimeDimension];

      // 计算电费数据
      const peakCost = currentData.peakData.map((val) => (val * 0.8).toFixed(2));
      const flatCost = currentData.flatData.map((val) => (val * 0.65).toFixed(2));
      const valleyCost = currentData.valleyData.map((val) => (val * 0.5).toFixed(2));

      const option = {
        title: {
          text: this.getTimeDimensionTitle(),
          left: "center",
          textStyle: {
            color: "#64748b",
            fontSize: 16,
            fontWeight: "bold",
          },
          top: 20,
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
          formatter: (params) => {
            let result = params[0].name + "<br/>";
            params.forEach((param) => {
              if (param.seriesType === "bar") {
                result += `<div style="display:flex;align-items:center;">
                  <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${param.color};"></span>
                  ${param.seriesName}: ${param.value} kWh
                </div>`;
              } else if (param.seriesType === "line") {
                result += `<div style="display:flex;align-items:center;">
                  <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${param.color};"></span>
                  ${param.seriesName}: ${param.value} 元
                </div>`;
              }
            });
            return result;
          },
        },
        legend: {
          data: [
            "峰时段电量",
            "平时段电量",
            "谷时段电量",
            "峰时段电费",
            "平时段电费",
            "谷时段电费",
          ],
          top: 50,
          textStyle: {
            color: "#64748b",
          },
          type: "scroll",
          pageIconColor: "#0066ff",
          pageIconInactiveColor: "#cccccc",
        },
        grid: {
          left: "8%",
          right: "8%",
          bottom: 0,
          top: "35%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: currentData.labels,
          axisLine: {
            lineStyle: {
              color: "rgba(0, 102, 255, 0.1)",
            },
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            color: "#64748b",
            fontSize: 12,
          },
        },
        yAxis: [
          {
            type: "value",
            name: "电量 (kWh)",
            position: "left",
            axisLine: {
              show: true,
              lineStyle: {
                color: "rgba(0, 102, 255, 0.1)",
              },
            },
            axisTick: {
              show: false,
            },
            splitLine: {
              lineStyle: {
                color: "rgba(0, 102, 255, 0.1)",
              },
            },
            axisLabel: {
              color: "#64748b",
              formatter: (value) => {
                return value;
              },
            },
            nameTextStyle: {
              color: "#64748b",
            },
          },
          {
            type: "value",
            name: "电费 (元)",
            position: "right",
            axisLine: {
              show: true,
              lineStyle: {
                color: "rgba(0, 102, 255, 0.1)",
              },
            },
            axisTick: {
              show: false,
            },
            splitLine: {
              show: false,
            },
            axisLabel: {
              color: "#64748b",
              formatter: (value) => {
                return value;
              },
            },
            nameTextStyle: {
              color: "#64748b",
            },
          },
        ],
        series: [
          {
            name: "峰时段电量",
            type: "bar",
            yAxisIndex: 0,
            data: currentData.peakData,
            itemStyle: {
              color: "#ff4444",
            },
            barWidth: "20%",
            barGap: "50%",
          },
          {
            name: "平时段电量",
            type: "bar",
            yAxisIndex: 0,
            data: currentData.flatData,
            itemStyle: {
              color: "#ffaa00",
            },
            barWidth: "20%",
            barGap: "50%",
          },
          {
            name: "谷时段电量",
            type: "bar",
            yAxisIndex: 0,
            data: currentData.valleyData,
            itemStyle: {
              color: "#00cc88",
            },
            barWidth: "20%",
            barGap: "50%",
          },
          {
            name: "峰时段电费",
            type: "line",
            yAxisIndex: 1,
            data: peakCost,
            itemStyle: {
              color: "#9333ea",
            },
            lineStyle: {
              width: 2,
            },
            symbolSize: 4,
            symbol: "circle",
            smooth: true,
          },
          {
            name: "平时段电费",
            type: "line",
            yAxisIndex: 1,
            data: flatCost,
            itemStyle: {
              color: "#3b82f6",
            },
            lineStyle: {
              width: 2,
            },
            symbolSize: 4,
            symbol: "circle",
            smooth: true,
          },
          {
            name: "谷时段电费",
            type: "line",
            yAxisIndex: 1,
            data: valleyCost,
            itemStyle: {
              color: "#ec4899",
            },
            lineStyle: {
              width: 2,
            },
            symbolSize: 4,
            symbol: "circle",
            smooth: true,
          },
        ],
      };

      this.peakValleyChart.setOption(option);
      window.addEventListener("resize", this.handleResize);
    },

    getTimeDimensionTitle() {
      const titles = {
        day: "日维度 - 峰谷平电量电费统计",
        month: "月维度 - 峰谷平电量电费统计",
        year: "年维度 - 峰谷平电量电费统计",
      };
      return titles[this.currentTimeDimension];
    },

    handleResize() {
      if (this.peakValleyChart) {
        this.peakValleyChart.resize();
      }
    },
    downloadChart() {
      if (!this.peakValleyChart) {
        console.error("图表实例不存在");
        return;
      }

      try {
        // 使用 ECharts 的 getDataURL 方法获取图片数据
        const dataURL = this.peakValleyChart.getDataURL({
          type: "png",
          pixelRatio: 2,
          backgroundColor: "#fff",
        });

        // 创建下载链接
        const link = document.createElement("a");
        link.download = `电费统计图表_${new Date().getTime()}.png`;
        link.href = dataURL;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (error) {
        console.error("下载图表失败:", error);
        // 如果需要，可以显示错误消息
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./EnergyAnalysis.scss";

.chart-container {
  height: 400px;
  position: relative;
  margin-bottom: 20px;
}

.chart-wrapper {
  width: 100%;
  height: 400px;
}

.trend-up {
  color: #10b981;
  font-weight: 500;
  font-size: 0.85rem;
  text-align: center;

  i {
    margin-right: 3px;
  }
}

.trend-down {
  color: #ef4444;
  font-weight: 500;
  font-size: 0.85rem;
  text-align: center;

  i {
    margin-right: 3px;
  }
}

.table-container {
  overflow-x: auto;
  margin-top: 20px;
  border-radius: 12px;
  border: 1px solid rgba(0, 102, 255, 0.1);
  background: rgba(248, 250, 252, 0.7);
}

.main-analysis {
  margin-top: 20px;
  border-radius: 12px;
  border: 1px solid rgba(0, 102, 255, 0.1);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.main-analysis-header {
  display: flex;
  align-items: center;
  font-size: 1.2rem;
  font-weight: 600;
  color: #0066ff;
  margin-bottom: 20px;

  .svg-icon {
    margin-right: 10px;
    font-size: 1.3rem;
    width: 1.3rem;
    height: 1.3rem;
  }
}

.main-analysis-content {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.main-analysis-content-item {
  background: #f8fafc;
  padding: 15px;
  border-radius: 8px;
  border: 1px solid #e2e8f0;

  div:first-child {
    font-size: 0.9rem;
    color: #64748b;
    margin-bottom: 8px;
  }

  .main-analysis-content-item-value {
    font-size: 1.1rem;
    font-weight: 600;
    color: #0066ff;
  }
}

.chart-legend {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 15px;
  flex-wrap: wrap;
  padding: 0 20px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 0.85rem;
  color: #64748b;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

@media (max-width: 768px) {
  .chart-card {
    flex-direction: column;

    .stat-card {
      width: 100%;
      margin-bottom: 15px;
    }
  }

  .main-analysis-content {
    grid-template-columns: 1fr;
  }

  .chart-wrapper {
    height: 300px;
  }

  .chart-legend {
    gap: 10px;
    flex-direction: row;
    flex-wrap: wrap;
  }

  .legend-item {
    font-size: 0.75rem;
    min-width: 30%;
    margin-bottom: 5px;
  }
}
</style>
